from flask import (Blueprint, request, session)
from flaskr.server.SheetsServer import *
from flaskr.Utils import *

bp = Blueprint('addField', __name__, url_prefix='/addField')


@bp.route('', methods = ['POST'])
def add_field():
    expression = request.json.get('expression')
    sheet_name = request.json.get('sheet_name')
    field_name = request.json.get('field_name')
    sheet = get_sheet(sheet_name)

    df = get_dataframe(sheet_name)

    df = addField(df, expression, field_name)

    if df is None:
        return{
            'code': 500,
            'msg': '添加列失败，请检查表达式是否正确'
        }

    if has_pkl(sheet_name):#如果是一个缓存的数据文件
        addPkl(df, sheet['md5'])
        df = df.head(200)

    sheet['table'] = dataFrameToHtml(df)
    sheet['columns'] = getColumns(df)
    sheet['json'] = dataFrameToJson(df)
    sheet['types'] = getTypes(df)

    set_sheet(sheet_name, sheet)

    sheet = get_sheet(sheet_name)
    return {
        'code': 200,
        'msg': '添加列成功',
        'data': sheet,
    }

def translate_format(expression):
    operator_list = ['+', '-', '*', '/']
    indexs = []

    start_point = 0
    end_point = 0
    count = 0
    now_count = 0

    for i in range(len(expression)):

        for operator in operator_list:
            symbol = expression[i]
            if symbol == operator and now_count >= count:
                end_point = i
                expression_len = len(expression)
                expression = translate_field(start_point, end_point, expression)

                start_point = len(expression) - expression_len + end_point + 1
                i = 0
                count = count + 1
                now_count = 0

            elif symbol == operator:
                now_count = now_count + 1

            else:
                continue

    # 结尾
    for operator in operator_list:
        index = expression.rfind(operator)
        indexs.append(index)

    indexs.sort()
    start_point = indexs[len(indexs) - 1] + 1
    end_point = len(expression)

    expression = translate_field(start_point, end_point, expression)

    return expression


def translate_field(start_point, end_point, expression):
    field_name = expression[start_point:end_point]

    index = field_name.rfind('(')
    if index != -1:
        start_point = start_point + index + 1

    index = field_name.find(')')
    if index != -1:
        end_point = start_point + index

    field_name = expression[start_point:end_point]

    try:
        int(field_name)
        return expression
    except:
        field_name_strip = 'df["' + field_name.strip() + '"]'
        expression = expression.replace(field_name, field_name_strip, 1)

        return expression


def addField(df, expression, field_name):
    res = translate_format(expression)

    try:
        df[field_name] = eval(res)
    except Exception as e:
        print(e)
        return None

    return df

